package com.leonzhangxf.spel.reference;

import com.leonzhangxf.spel.reference.bean.Society;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

/**
 * Ternary Operator (If-Then-Else)
 *
 * You can use the ternary operator for performing if-then-else conditional logic inside the expression.
 *
 * @author leonzhangxf
 * @date 20190427
 */
public class TernaryOperator {

    public static void main(String[] args) {
        ExpressionParser parser = new SpelExpressionParser();

        System.out.println(parser.parseExpression("false ? 'trueExp' : 'falseExp'")
            .getValue(String.class));


        StandardEvaluationContext societyContext = new StandardEvaluationContext();
        Society society = new Society();
        societyContext.setRootObject(society);

        parser.parseExpression("Name").setValue(societyContext, "IEEE");
        societyContext.setVariable("queryName", "Nikola Tesla");

        String expression = "isMember(#queryName)? #queryName + ' is a member of the ' + Name + ' Society' " +
            ": #queryName + ' is not a member of the ' + Name + ' Society'";
        String queryResultString = parser.parseExpression(expression)
            .getValue(societyContext, String.class);
        System.out.println(queryResultString);
        // queryResultString = "Nikola Tesla is a member of the IEEE Society"
    }
}
